package com.hankol.community

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.view.View
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.BaseConstant
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.ARouterUtils.parseParams
import com.baselibrary.utils.EventBusUtils.sendNotify1Value
import com.baselibrary.view.share.SharePopupWindow
import com.hankol.message.HKIMUtils
import com.hankol.community.arouter.CommunityHelp
import com.baselibrary.bean.TimelineInfoData
import com.hankol.community.databinding.ActivityPictureDetailsBinding
import com.hankol.community.viewmodel.PictureDetailsViewModel
import com.liaoinstan.springview.utils.DensityUtil
import com.like.LikeButton
import com.like.OnLikeListener
import com.okhttp.comment.BaseCommentAdapter
import com.okhttp.comment.CommentBean
import com.okhttp.comment.CommentConstant
import com.okhttp.comment.IPCommentListener
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @description 图片详情
 * @author 关忆北、
 * @time 2022/5/5 10:32 上午
 */
@Route(path = ActivityRouter.ACTIVITY.IMAGE_DETAIL)
class PictureDetailsActivity : BaseActivity(), View.OnClickListener {
    val communityHelp: CommunityHelp =
            ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private lateinit var mDataBinding: ActivityPictureDetailsBinding
    private lateinit var mViewModel: PictureDetailsViewModel
    private var mPage: Int = 1
    private var mPictureId: Long = 0
    private var mSourceName = ""
    private var mToppingCommentId: Long = 0
    private var mCommentBean: CommentBean.DataBean? = null
    private var mDataBean: TimelineInfoData.ClientTimeline? = null
    private var mShowSharePop: SharePopupWindow? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_picture_details
    }

    override fun init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//共享元素 解决白屏
            postponeEnterTransition();
        }
        mDataBinding = getDataBinding<ActivityPictureDetailsBinding>()
        mViewModel = getActivityViewModelProvider(this).get(PictureDetailsViewModel::class.java)
        mViewModel.mDataBinding = mDataBinding
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        //兼容统一路由跳转
        intent.extras?.let {
            mPictureId = parseParams(it, "id")[0].toLong()
            mSourceName = parseParams(it, "source")[0]
            if (parseParams(it, Constants.COMMENT_TOP_ID)[0].checkNotNull()) {
                mToppingCommentId = parseParams(it, Constants.COMMENT_TOP_ID)[0].toLong()
            }
        }
        SensorsDataManager.instance.onCreateTime()
        initView()
        initObserve()
        initData()
        initListener()
        SensorsDataManager.instance.setFormPagePos("动态")
    }

    private fun initView() {
        mDataBinding.tvPictureDetIndex.paint.isFakeBoldText = true
        mDataBinding.BaseCommentViewImageDynamic.setEmptyImgSize(DensityUtil.dip2px(applicationContext, 230f), DensityUtil.dip2px(applicationContext, 230f))
        mDataBinding.BaseCommentViewImageDynamic.setAdapter(this, IPCommentListener(this, mDataBinding.BaseCommentViewImageDynamic))

    }

    private fun initObserve() {
        mViewModel.commentListLiveData.observe(this, Observer {
            mDataBinding.springPicture.finishRefresh()
            mDataBinding.springPicture.finishLoadMore()
            mDataBinding.BaseCommentViewImageDynamic.commentNetData(it, mPage)
            if (it != null) {
                mCommentBean = it
                mDataBinding.tvPictureDetSumComment.text = "共${it.totalCount}条评论"
                mDataBinding.includeCommentView.tvCommentComCount.text =
                        if (it.totalCount == 0) "抢首评" else NumberUtils.formatBigNum(it.totalCount.toString())
                if (mToppingCommentId > 0) {
                    mDataBinding.tvPictureDetSumComment.post {
                        mDataBinding.scrollView.smoothScrollTo(0, mDataBinding.tvPictureDetSumComment.top)
                        mToppingCommentId = 0
                    }
                }
                mPage++
            }
        })

        mViewModel.dynamicLiveData.observe(this, Observer {
            hideLoadingDialog()
            if (it != null) {
                mDataBean = it
                mViewModel.initView(it, this)
            }
        })

        mViewModel.followLiveData.observe(this, Observer {
            if (it.flag) {
                mDataBean?.user?.isFocusFans = !mDataBinding.ivPictureDetFollow.isSelected
                mDataBinding.ivPictureDetFollow.setImageResource(if (!mDataBinding.ivPictureDetFollow.isSelected) R.drawable.ic_picture_true_follow else R.drawable.ic_picture_flase_follow)
                mDataBinding.ivPictureDetFollow.isSelected =
                        !mDataBinding.ivPictureDetFollow.isSelected

                sendNotify1Value(MessageBus.msgId_follow_and_cancel, 0)
                if (mDataBean?.user?.isFocusFans!!) {
                    //关注
                    HKIMUtils.followSendMsg(mDataBean?.user?.id?.toInt()!!, it.friendState)
                }
            }
        })

        mViewModel.collectionLiveData.observe(this, Observer { it ->
            if (it) {
                mDataBinding.includeCommentView.ivCommentConState.isEnabled = true
                mDataBean?.let {
                    it.isFavorited = !mDataBinding.includeCommentView.llCommentCollection.isSelected
                    it.favoriteNum =
                            if (mDataBinding.includeCommentView.llCommentCollection.isSelected) {
                                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "取消收藏")
                                it.favoriteNum.minus(1)
                            } else {
                                ToastUtils.showShort(ContextUtils.getCurApplication().applicationContext, "收藏成功")
                                it.favoriteNum.plus(1)
                            }
                    mViewModel.upCollectionSate(it)
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_collect_status, it.id.toInt())
                }
            }
        })

        mViewModel.supportLiveData.observe(this, Observer { it ->
            mDataBinding.includeCommentView.ivCommentGiveState.isEnabled = true
            if (it) {
                mDataBean?.let {
                    it.isSupported = !mDataBinding.includeCommentView.llCommentGive.isSelected
                    it.supportNum =
                            if (mDataBinding.includeCommentView.llCommentGive.isSelected) it.supportNum.minus(1) else it.supportNum.plus(1)
                    mViewModel.upSupportSate(it)
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_change_dynamic_like_status, it.id.toInt())
                }
            }
        })
        mViewModel.friendLiveData.observe(this, Observer {
            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })

        mViewModel.shareAddNumLD.observe(this, Observer {
            //分享次数+1 成功
        })
    }

    private fun initData() {
        showLoadingDialog()
        mViewModel.reqDynamicDetails(mPictureId)
        mViewModel.reqCommentList(mPage, mPictureId, mToppingCommentId)
    }

    private fun initListener() {
        mDataBinding.ivPictureDetBack.setOnClickListener(this)
        mDataBinding.ivPictureDetShare.setOnClickListener(this)
        mDataBinding.tvPictureDetTopic.setOnClickListener(this)
        mDataBinding.vipPictureDetHead.setOnClickListener(this)
        mDataBinding.ivPictureDetFollow.setOnClickListener(this)
        mDataBinding.tvPictureDetComment.setOnClickListener(this)
        mDataBinding.circlePictureDetCurrentHead.setOnClickListener(this)
        mDataBinding.BaseCommentViewImageDynamic.setEmptyViewListener(this)
        mDataBinding.includeCommentView.llCommentGive.setOnClickListener(this)
        mDataBinding.includeCommentView.llCommentJumpCom.setOnClickListener(this)
        mDataBinding.includeCommentView.llCommentCollection.setOnClickListener(this)
        mDataBinding.includeCommentView.llCommentSaySomething.setOnClickListener(this)

        mDataBinding.includeCommentView.ivCommentGiveState.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //点赞
                mDataBinding.includeCommentView.ivCommentGiveState.isEnabled = false
                if (mDataBean!=null) {
                    mViewModel.reqSupport(true, 4, mDataBean?.id!!.toInt())
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消点赞
                mDataBinding.includeCommentView.ivCommentGiveState.isEnabled = false
                if (mDataBean!=null) {
                    mViewModel.reqSupport(false, 4, mDataBean?.id!!.toInt())
                }
            }
        })
        mDataBinding.includeCommentView.ivCommentConState.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                //收藏
                mDataBinding.includeCommentView.ivCommentConState.isEnabled = false
                if (mDataBean!=null) {
                    mViewModel.reqCollection(true, 4, mDataBean?.id!!)
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                //取消收藏
                mDataBinding.includeCommentView.ivCommentConState.isEnabled = false
                if (mDataBean!=null) {
                    mViewModel.reqCollection(false, 4, mDataBean?.id!!)
                }
            }
        })
        mDataBinding.vpPictureDetPicture.setOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(i: Int, v: Float, i1: Int) {}

            @SuppressLint("SetTextI18n")
            override fun onPageSelected(i: Int) {
                var onPageSelectedPos = 0
                if (i != 0 && mDataBean?.images?.size!! > 0) {
                    onPageSelectedPos = i % mDataBean?.images?.size!!
                }
                mDataBinding.tvPictureDetIndex.text = "${(onPageSelectedPos + 1)}/${mDataBean?.images?.size!!}"

                mDataBinding.indicatorPicture.setCurrentShowView(onPageSelectedPos)
            }

            override fun onPageScrollStateChanged(i: Int) {}
        })
        mDataBinding.springPicture.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                mPage = 1
                mViewModel.reqCommentList(mPage, mPictureId, 0)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                val commentNorMarAdapter: BaseCommentAdapter =
                        mDataBinding.BaseCommentViewImageDynamic.commentAdapterType
                mCommentBean?.let {
                    if (it.count <= commentNorMarAdapter.itemCount) {
                        mDataBinding.springPicture.finishRefresh()
                        mDataBinding.springPicture.finishLoadMore()
                        return
                    }
                }
                mPage++
                mViewModel.reqCommentList(mPage, mPictureId, 0)
            }

        })
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.circle_pictureDet_currentHead -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage()
                    return
                }
                //个人主页
                val hashMap = HashMap<String, Any>()
                hashMap[BaseConstant.USER_ID] = SpUtils.getInstance().userId
                ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
            }
            R.id.vip_pictureDet_head -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                //个人主页
                mDataBean?.let {
                    val hashMap = HashMap<String, Any>()
                    hashMap[BaseConstant.USER_ID] = it.uid
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap)
                }
            }
            R.id.iv_pictureDet_back -> onBackPressed()
            R.id.iv_pictureDet_follow -> {
                mDataBean?.let {
                    mViewModel.reqFollow(this, !mDataBinding.ivPictureDetFollow.isSelected, 1, it.user.id)
                }
            }

            R.id.tv_pictureDet_topic -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                //话题
                if (mDataBean?.tagIds.checkNotNull()) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["tid"] = mDataBean?.tagIds!![0]
                    hashMap["tsource"] = "动态内部"
                    ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL, hashMap)
                }
            }

            R.id.ll_comment_give -> {
                //点赞
                mViewModel.reqSupport(!mDataBinding.includeCommentView.llCommentGive.isSelected, 4, mDataBean?.id!!.toInt())
            }
            R.id.ll_comment_collection -> {
                //收藏
                mViewModel.reqCollection(!mDataBinding.includeCommentView.llCommentCollection.isSelected, 4, mDataBean?.id!!)

            }
            R.id.iv_pictureDet_share -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                //分享
                mDataBean?.let {
                    mShowSharePop = mViewModel.showShare(it, this, communityHelp)
                    mViewModel.reqFriendList()
                }
            }
            R.id.ll_comment_jumpCom -> {
                mDataBinding.tvPictureDetSumComment.post {
                    mDataBinding.scrollView.smoothScrollTo(0, mDataBinding.tvPictureDetSumComment.top)
                }
                if (DoubleClickHelper.isOnDoubleClick()) return
                //评论弹窗
                mDataBean?.user?.let {
                    communityHelp.openCommentActivity(this, 6, mPictureId.toInt(), mDataBinding.includeCommentView.tvCommentSaySomething.text
                            .toString()
                            .trim(), it.name.checkValue(), false, CommentConstant.COMMENT_REQUESTCODE)
                }
            }
            R.id.ll_base_comment_empty,
            R.id.tv_pictureDet_comment,
            R.id.ll_comment_saySomething -> {
                if (DoubleClickHelper.isOnDoubleClick()) return
                //进行评论
                mDataBean?.user?.let {
                    communityHelp.openCommentActivity(this, 6, mPictureId.toInt(), mDataBinding.includeCommentView.tvCommentSaySomething.text
                            .toString()
                            .trim(), it.name.checkValue(), false, CommentConstant.COMMENT_REQUESTCODE)
                    BaseConstant.loadCommentEventBusBean("动态", "内容详情页")//埋点
                }

            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mDataBinding.BaseCommentViewImageDynamic.commentOnResult(requestCode, resultCode, data)
        mDataBinding.BaseCommentViewImageDynamic.setSayContent(requestCode, resultCode, data, mDataBinding.includeCommentView.tvCommentSaySomething, CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
        val commentNum: Int = mDataBinding.BaseCommentViewImageDynamic.upCommentNum(requestCode, resultCode, data, mDataBean?.commentNum!!, mDataBinding.includeCommentView.tvCommentComCount)
        if (commentNum != -1) {
            mDataBean?.commentNum = commentNum
            mDataBinding.tvPictureDetSumComment.text = "共${commentNum}条评论"
        }
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_follow_and_cancel) {
            mViewModel.reqDynamicDetails(mPictureId)
        } else if (messageBus.codeType == MessageBus.msgId_share_success) {
            mDataBean?.let {
                mViewModel.reqAddShareNum(it.id)//分享次数+1
            }
        }
    }

    override fun onDestroy() {
        mDataBean?.let {

        }
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        mViewModel.sensors(mDataBean, mSourceName)
    }
}